// tcp.cpp
#include "tcp.h"
#include "..\..\login.h"           // 包含登录窗口的头文件
#pragma comment(lib, "ws2_32.lib") // 添加库链接指令
SOCKET listenFd;                   // 套接字
HANDLE Tcp_hThread;                // 线程句柄


tcp::tcp() : QObject(nullptr) // 显式调用QObject的构造函数
{
    // 0 确定通信协议版本
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (2 != HIBYTE(wsaData.wVersion) || 2 != LOBYTE(wsaData.wVersion))
    {
        qDebug() << "tcp----3 banBen err" << endl;
    }

    listenFd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == listenFd)
    {
        qDebug() << "create socket err:%m" << endl;
        // exit(-1);
    }
    qDebug() << "create socket ok:%m" << endl;

    // 2 设置服务器协议地址
    struct sockaddr_in sAddr = {0};
    sAddr.sin_family = AF_INET;
    // sAddr.sin_addr.s_addr = inet_addr("192.168.124.28"); // 家里的 IP 地址
    sAddr.sin_addr.s_addr = inet_addr("192.168.70.230"); // 教室 IP 地址
    sAddr.sin_port = htons(9999);

    // 3 连接服务器
    int r = ::connect(listenFd, (struct sockaddr *)&sAddr, sizeof(sAddr)); // 使用::connect调用Winsock的connect函数
    if (-1 == r)
    {
        qDebug() << "connect err:%m" << endl;
        closesocket(listenFd);
        WSACleanup();
        // exit(-1);
    }
    qDebug() << "connect ok!" << endl;
}

// 接受服务器返回的请求子线程
DWORD WINAPI Tcp_handle_sonFn(LPVOID lpParameter)
{
    char buffData[2048];
    while (1)
    {
        // 从服务器接收数据
        int r = recv(listenFd, buffData, sizeof(buffData), 0);
        if (r > 0)
        {
            qDebug() << "接收到数据" << buffData << ",长度" << strlen(buffData) << endl;

            if (buffData[0] == '1' && buffData[1] == '0' && buffData[2] == '0' && buffData[3] == '0')
            {
                if (buffData[5] == 'x')
                {
                    // MessageBox(NULL, "账号或密码错误", "错误", MB_OK | MB_ICONERROR);
                    qDebug() << "账号或密码错误" << endl;
                    // QMessageBox::information(this, "登录失败", "用户名：" + accountValue + "\n密码：" + passwordValue + ",账号或密码错误");
                }
                else
                {
                    qDebug() << "登录接口返回值" << buffData << endl;
                    int count = 0;
                    // 调用函数拆分字符串
                    const char delim = '^';
                    int arrayLength = 0;
                    char **tokens = splitStringCorrect(buffData, delim, &arrayLength);
                    for (int i = 0; i < arrayLength; i++)
                    {
                        printf("tokens[%d]: %s\n", i, tokens[i]);
                    }
                    qDebug() << tokens[0] << "," << tokens[1] << "," << tokens[2] << "," << tokens[3] << "," << tokens[4] << "," << tokens[5] << "," << tokens[6] << "," << tokens[7] << "," << tokens[7] << endl;
                    uid = atoi(tokens[2]);
                    sex = atoi(tokens[3]);
                    userName = tokens[6];
                    niceName = tokens[7];
                    qDebug() << "登录成功,跳转首页窗口" << endl;
                    
                    // 弹出一个信息框，显示登录成功
                    // QMessageBox::information(this, "登录成功", "用户名：" + accountValue + "\n密码：" + passwordValue);
                }
            }
        }
        else if (r == 0)
        {
            printf("连接已关闭\n");
            break;
        }
        else
        {
            perror("接收错误");
            // 可以根据错误类型进行重试或其他处理
            break;
        }

        // 根据实际情况调整 Sleep 时间或使用更高效的等待机制
        Sleep(10); // 减少 CPU 占用
    }

    return 0; // 线程正常退出
}

// 发送请求
int tcp::tcp_send(int i)
{
    // 创建子线程接收数据
    Tcp_hThread = CreateThread(NULL, 0, Tcp_handle_sonFn, (LPVOID)listenFd, 0, NULL);
    if (Tcp_hThread == NULL)
    {
        qDebug() << "创建子线程失败";
        return 0;
    }
    char query[1024] = {0};
    if (i == 1000) // 登录
    {
        qDebug() << "账号：" << accountValue << endl;
        qDebug() << "密码：" << passwordValue << endl;
        memset(query, 0, sizeof(query));
        // 接口id、账号、密码
        sprintf(query, "%d^%s^%s", 1000, accountValue.toUtf8().constData(), passwordValue.toUtf8().constData());
    }

    query[sizeof(query) - 1] = '\0';
    qDebug() << "发送数据--------" << query << endl;
    int bytesSent = send(listenFd, (const char *)&query, sizeof(query), 0);
    if (bytesSent == -1)
    {
        qDebug() << "send error";
        return 0;
    }
    return 1;
}
